package class202205.demo20.demo19.Heap;

import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    /**
     * 向下调整函数的实现
     * @param parent 没课树的根节点
     * @param len 每棵树的结束位置
     */
//向下调整
    public void shiftDown(int parent,int len){
        int child = 2*parent+1;
        //最起码有左孩子
        while (child<len){

            //如果没有右孩子 数组越界  得加条件child+1<len
            if (child+1<len && elem[child]<elem[child+1]){
                child++;//保证当前孩子最大值的下标
            }
            if (elem[child]>elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent]= tmp;
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }

//创建一个大根堆   创建一个数组  把元素放进来
    public void createHeap(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
        //确定最后一个下标的根节点 parent
        for (int parent = (usedSize-2)/2; parent >=0; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    /**
     * 入队操作  保证如对后仍然保持大根堆
     * 向上调整
     * @param val
     */
    public void offer(int val){

        if (isFull()){
            //扩容
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        //注意传参
        shiftUp(usedSize-1);
    }
//向上调整
    private void shiftUp(int child){
        int parent = (child-1)/2;
        while (child > 0){
            if (elem[child]>elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent]= tmp;
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }
    //当前队列是否为满
    public boolean isFull(){
        return usedSize == elem.length;
    }

    public int poll(){
        if (isFull()){
            throw new RuntimeException("优先级队列为空！");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        //调用向下调整
        shiftDown(0,usedSize);
        return tmp;
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }

    public void heapShort(){
        int end = usedSize-1;
        while (end!=0){
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = elem[0];
            shiftDown(0,end);
            end--;
        }
    }
}
